import { defineStore } from "pinia";
import { ref } from "vue";
import apiClient from "../utils/appHttp";

export const useUserStore = defineStore("user",()=>{

    const userName = ref(null)

    async function login(username:string,password:string) {
        console.log("login",username,password);
        let res = await apiClient.post('/auth',{
            'action':'login',
            'username':username,
            'password':password
        })
        console.log("login res,",res)
        console.log(res.data.code);
        console.log(res.data.code,res.data.code==0)
        if(res.data.code!=0) {
            console.log("login error:",res.data.message)
            throw new Error(res.data.message)
        }
        userName.value = res.data.data.username;
        localStorage.setItem('token',res.data.data.token)
        
    }

    async function fetchUserInfo() {
        if(userName.value!=null) {
            return;
        }
        let res = await apiClient.post('/auth',{
            'action':'getProfile'
        })
        if(res.data.code === 0) {
            userName.value = res.data.data.username;
        }
    }
    function logout() {
        userName.value = null
        localStorage.removeItem('token')

    }
    return {
        userName,
        login,
        logout,
        fetchUserInfo

    }
})